import { Client } from 'pg';
import bcrypt from 'bcrypt';

// 直接写死连接配置，忽略 process.env
const client = new Client({
    host: '43.162.111.101',
    port: 5432,
    user: 'myuser',
    password: '123456',
    database: 'dating_app',
});

async function hashPasswords() {
    await client.connect();

    // 先查询所有用户
    const res = await client.query('SELECT id, password FROM users');
    console.log(`共找到 ${res.rows.length} 个用户`);

    let count = 0;

    for (const row of res.rows) {
        const oldPassword = row.password;

        // 跳过已加密的
        if (oldPassword.startsWith('$2b$')) continue;

        const hashed = await bcrypt.hash(oldPassword, 10);
        await client.query('UPDATE users SET password = $1 WHERE id = $2', [hashed, row.id]);
        count++;
    }

    console.log(`✅ 已成功加密 ${count} 个用户密码`);
    await client.end();
    console.log('🎉 所有密码已更新为 bcrypt 哈希格式');
}

hashPasswords().catch((err) => {
    console.error('❌ 出错:', err);
    process.exit(1);
});
